/**
 * Created by 19110 on 2016/10/14.
 */

$().ready(function () {
    $("#btn_send").hide();
});

var ws;

function connect() {
    if ("WebSocket" in window) {
        // alert("您的浏览器支持 WebSocket!");

        var token = $.cookie('token');
        // 打开一个 web socket
        var host = window.location.host;
        var hostname = window.location.hostname;
        console.log("host:" + host);
        console.log("hostname:" + hostname);
        ws = new WebSocket("ws://" + hostname + ":8080/chat?token=" + token);

        ws.onopen = function () {
            // Web Socket 已连接上，使用 send() 方法发送数据
            console.log("已连接");
            $("#btn_send").show();
            $("#btn_connect").hide();
        };

        ws.onmessage = function (evt) {
            var received_msg = evt.data;
            console.log(received_msg);
            var msg_json = JSON.parse(received_msg);
            $("#msgBox").append(createMsgRow(msg_json.username, msg_json.msg, false));
        };

        ws.onclose = function () {
            // 关闭 websocket
            alert("连接已关闭...");
            $("#btn_send").hide();
            $("#btn_connect").show();
        };
    } else {
        // 浏览器不支持 WebSocket
        alert("您的浏览器不支持 WebSocket!");
    }
}

function close() {
    ws.close();
}

function createMsgRow(sender, msg, isMyMsg) {
    if (isMyMsg) {
        return '<div align="right" class="alert-success">' + sender + ' ：<br>' + msg + '</div>'
    } else {
        return '<div align="left" class="alert-info">' + sender + ' ：<br>' + msg + '</div>'
    }
}

function sendMsg() {
    var msg = $("#msgToSend").val();
    if (msg.trim() == "") {
        return;
    }
//        $("#msgBox").append(createMsgRow(msg, false));
    ws.send(msg);
    $("#msgBox").append(createMsgRow('我', msg, true));
    $("#msgToSend").val("");
}